import { watch } from 'vue';
import { THEME_DARK, THEME_LIGHT, THEME_SYSTEM } from '@/constants';
import { useThemeStore } from '@/store';

let matchMedia: MediaQueryList;

function changeTheme(
  newTheme: typeof THEME_LIGHT | typeof THEME_DARK | typeof THEME_SYSTEM
) {
  let themeClass = '';
  switch (newTheme) {
    case THEME_LIGHT:
      themeClass = 'light';
      break;
    case THEME_DARK:
      themeClass = 'dark';
      break;
    case THEME_SYSTEM:
      watchSystemThemeChange();
      themeClass = matchMedia.matches ? 'dark' : 'light';
      break;
  }

  document.documentElement.className = themeClass;
}

const watchSystemThemeChange = () => {
  if (matchMedia) return;

  matchMedia = window.matchMedia('(prefers-color-scheme: dark)');

  matchMedia.onchange = () => {
    changeTheme(THEME_SYSTEM);
  };
};

const useTheme = () => {
  const { themeTypeGetter: theme } = useThemeStore();

  watch(theme, changeTheme, {
    immediate: true
  });
};

export default useTheme;
